import React, { Component ,ComponentClass} from 'react';
import {AtForm, AtInput, AtIcon, AtModal} from "taro-ui";
import Taro from '@tarojs/taro';
import {View} from '@tarojs/components'
import {http} from '../../utils/http'
import {
  BASE_URL,
  UPLODE_FALE,
  OCR, FACE,
  materialMedia
} from '../../constants/api'
import {platform} from "../../utils/platform-settting.service";
import {newHttp} from "../../utils/request";
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {lxH5Wx} from "../../utils/lx.h5.service";
import './addcontact.scss'

interface pageState {
  idcardTime: number
  contactData: {
    idcard: string
    name: string
    phone: string
  }
  idx: number
  delModal: boolean
  isSunmit: boolean
}

type PageOwnProps = {}
type PageState = {}

class addcontact extends Component {
  state: pageState = {
    idcardTime: 0,
    contactData: {
      idcard: '',
      name: '',
      phone: '',
    },
    idx: 0,
    delModal: false,
    isSunmit: false,
  }
  async componentDidShow(){
    vcmonitor(this);
    this.setState({
      idx: Taro.getCurrentInstance().router.params.idx,
    }, async () => {
      if (this.state.idx) {
        const contactData = JSON.parse(Taro.getStorageSync('teamAppoint'))[+this.state.idx]
        this.setState({
          contactData: contactData
        })
      }
    })
  }
  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const platformSet = await platform.getSetting()
    if (platformSet.platformName) {
      Taro.setNavigationBarTitle({
        title: platformSet.platformName
      })
    }
  }

  // 保存
  async contactAdd(type, show = true) {
    const {contactData, idx, isSunmit} = this.state
    if (isSunmit) return
    this.setState({isSunmit: true})
    const time = setTimeout(() => {
      this.setState({isSunmit: false})
      clearTimeout(time)
    }, 2000)
    const r = /^1[0-9]{10}$/;　　//1开头0-9内十位数
    const n = /^(?:[\u4e00-\u9fa5·]{2,16})$/;　　//中文
    if (!r.test(contactData.phone)) {
      Taro.showToast({title: '手机号码格式不正确', icon: 'none'})
      return false
    }
    if (idx) {
      const teamAppoint = JSON.parse(Taro.getStorageSync('teamAppoint'))
      teamAppoint[idx] = contactData
      Taro.setStorageSync('teamAppoint', JSON.stringify(teamAppoint))
      setTimeout(() => {
        this.setState({ contactData: { idcard: '', name: '', phone: '', } });
      }, 100);
      if (show) {
        Taro.showToast({title: '修改成功', icon: 'none'})
        if (type == 1) {
          const time = setTimeout(() => {
            clearTimeout(time)
            Taro.navigateBack({
              delta: 1
            })
          }, 300)
        }
      }
    } else {
      let teamAppoint = Taro.getStorageSync('teamAppoint')
      teamAppoint = teamAppoint ? JSON.parse(teamAppoint) : []
      Taro.showToast({title: '保存成功', icon: 'none'})
      if (teamAppoint && teamAppoint.length > 0) {
        teamAppoint.push(contactData)
        Taro.setStorageSync('teamAppoint', JSON.stringify(teamAppoint))
      } else {
        Taro.setStorageSync('teamAppoint', JSON.stringify([contactData]))
      }
      setTimeout(() => {
        this.setState({ contactData: { idcard: '', name: '', phone: '', } });
      }, 100);
      if (type === 1) {
        const time = setTimeout(() => {
          clearTimeout(time)
          Taro.navigateBack({
            delta: 1
          })
        }, 300)
      }
    }
  }

  handleChange(name, value) {
    const {contactData} = this.state
    contactData[name] = value.replace(/\s+/g, '')
    this.setState({contactData})
  }

  async delLink() {
    this.setState({delModel: true})
    const teamAppoint = JSON.parse(Taro.getStorageSync('teamAppoint'))
    teamAppoint.splice(this.state.idx, 1)
    Taro.setStorageSync('teamAppoint', JSON.stringify(teamAppoint))
    Taro.showToast({title: '删除成功', icon: "none"})
    const time = setTimeout(() => {
      clearTimeout(time)
      Taro.navigateBack({
        delta: 1
      })
    }, 2000)
  }

  uplodeImg(group = 0) {
    const that = this
    let {upCount, contactData, idcardTime} = this.state
    contactData['idcard']  = ''
    this.setState({contactData})
    const apiList = [OCR, UPLODE_FALE, FACE]
    const api = BASE_URL + apiList[group]
    if (process.env.TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.chooseImage(async (files, length) => {
          lxH5Wx.uploadOcr(files, length, (data) => {
            contactData.idcard = data.idcard
            that.setState({contactData})
          })
        }, 1)
      } else {
        h5Wx.chooseImage(1, ret => {
          Taro.showToast({
            title: group === 0 ? '正在识别...' : '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          h5Wx.wxuploadImage(ret, async res => {
            if (group == 1) {
              const dataRet = await newHttp.catchGet(materialMedia + res, {})
              console.log(dataRet)
              if (dataRet) {
                Taro.hideToast();
                if (dataRet) {
                  contactData['upload_file'].push(dataRet)
                  that.setState({contactData, idcardTime}, () => {
                    console.log(that.state.contactData)
                  })
                }
              }
            } else {
              const dataRet = await newHttp.catchPost(api, {media_id: res}, true)
              uploadImgCount++;
              Taro.hideToast();
              const data = dataRet;
              if (dataRet.status == 400) {
                Taro.showToast({
                  title: data.message,
                  icon: 'none'
                })
                return
              }
              if (group === 0) {
                if (data && data.idcard) {
                  contactData.idcard = data.idcard
                  idcardTime++
                }
              }
              that.setState({contactData, idcardTime}, () => {
              })
            }
          })
        })
      }
    } else {
      Taro.chooseImage({
        count: upCount,  //最多可以选择的图片总数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          //启动上传等待中...
          Taro.showToast({
            title: group === 2 ? '正在识别...' : '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            console.log(tempFilePaths[i])
            Taro.uploadFile({
              url: api,
              filePath: tempFilePaths[i],
              name: group === 2 ? 'face' : 'file',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                uploadImgCount++;
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                if (group === 0) {
                  if (data.data && data.data.idcard) {
                    contactData.idcard = data.data.idcard
                    idcardTime++
                  }
                }
                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  that.setState({contactData, idcardTime}, () => {
                  })
                  Taro.hideToast();
                }
              },
              fail: function (res) {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false,
                  success: function (res) {
                  }
                })
              }
            });
          }
        }
      })
    }
  }

  render() {
    const {idcardTime, contactData, idx, delModal} = this.state
    return (
      <View className='addcontact-root'>
        <GzhAuth />
        <AtForm className='person' customStyle='margin-top:20rpx;'>
          <AtInput clear className='require' name='name' type='text'
            maxLength={15}
            value={contactData.name} title='姓名' placeholder='购买人的真实姓名'
            onChange={this.handleChange.bind(this, 'name')}
          />
          <AtInput maxLength={11} clear className='require' name='phone' type='number'
            value={contactData.phone} title='手机号码' placeholder='购买人手机号'
            onChange={this.handleChange.bind(this, 'phone')}
          />
          <AtInput maxLength={18} clear key={idcardTime} name='idcard' type='idcard'
            value={contactData.idcard} title='身份证号' placeholder='购买人身份证号'
            onChange={this.handleChange.bind(this, 'idcard')}
          >
            <AtIcon onClick={this.uplodeImg.bind(this, 0)} prefixClass='car' value='iconhexiao2' size='18'
              color='#FCAA09'
            />
          </AtInput>
        </AtForm>
        <View className='btn_box'>
          {!idx && <View onClick={this.contactAdd.bind(this)} className='save-add-btn'>保存并继续新增</View>}
          {idx && <View onClick={() => {
            this.setState({delModal: true})
          }} className='save-add-btn'
          >删除</View>}
          <View onClick={this.contactAdd.bind(this, 1)} className='save-btn'>保存</View>
        </View>
        <AtModal
          isOpened={delModal}
          cancelText='取消'
          confirmText='确认'
          onClose={() => {
            this.setState({delModal: false})
          }}
          onCancel={() => {
            this.setState({delModal: false})
          }}
          onConfirm={this.delLink.bind(this)}
          content='是否确定删除?'
        />
      </View>
    )
  }
}

export default addcontact as ComponentClass<PageOwnProps, PageState>
